<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Models\NsSupplierGoods;
use App\Models\XnBatchOrder;
use App\Models\XnH5Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class H5OrderController extends Controller
{
    // 供应商H5订单列表
    public function merchantH5Order(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'account' => 'nullable|string|max:100',         // 充值账号
            'goodsId' => 'nullable|integer|min:1',         // 商品ID
            'goods_code' => 'nullable|string|max:50',      // 商品代码
            'recharge_status' => 'nullable|integer',       // 订单状态
            'start_time' => 'nullable|date',               // 开始时间
            'end_time' => 'nullable|date|after:start_time',// 结束时间
            'order_sn' => 'nullable|string|max:50',        // 商户订单号
            'third_order' => 'nullable|string|max:50',     // 外部订单号
            'mecahnt_num' => 'nullable|string|max:50',     // 商户号
        ]);

        try {
            $query = XnBatchOrder::query()->with('couponInfo:order_sn,price,coupon')->where('business', 99)
                ->orderByDesc('id');

            // 时间范围筛选
            if (!empty($validated['start_time']) && !empty($validated['end_time'])) {
                $query->whereBetween('recharge_time', [
                    $validated['start_time'],
                    $validated['end_time']
                ]);
            }

            // 动态添加筛选条件
            $filters = [
                'Merchant_number' => $validated['mecahnt_num'] ?? null,
                'merchantOrderNum' => $validated['third_order'] ?? null,
                'goodsId' => $validated['goodsId'] ?? null,
                'goods_code' => $validated['goods_code'] ?? null,
                'orderNum' => $validated['order_sn'] ?? null,
                'userName' => $validated['account'] ?? null,
            ];
            if(isset($validated['recharge_status']) && $validated['recharge_status'] != null){
                if($validated['recharge_status'] == 0){
                    $query->whereIn('recharge_status', [0,3]);
                }else{
                    $query->where('recharge_status', $validated['recharge_status']);
                }
            }
            foreach ($filters as $field => $value) {
                if (!empty($value)) {
                    $query->where($field, $value);
                }
            }
            $orders = $query->orderByDesc('recharge_time') -> paginate(10);
            $orders->getCollection()->transform(function ($order){
                $order->rechargeMoney = $order->couponInfo ? round($order->rechargeMoney-$order->couponInfo->price,4) : $order->rechargeMoney;
                return $order;
            });
            return successly($orders);
        } catch (\Throwable $e) {
            dump($e -> getMessage());
            dump($e->getLine());
            return fails('订单查询失败，请稍后重试');
        }
    }

    // H5端订单列表
    public function h5Order(Request $request): JsonResponse
    {
        try {
            $userId = auth('h5user')->id();
            $searchTerm = $request->post('info', '');
            $rechargeStatus = $request->post('status', '');
            $start_time = $request->post('start_time', '');
            $end_time = $request->post('end_time', '');

            // 基础查询
            $query = XnH5Order::query()->where('user', $userId)
                ->where('is_pay', 1)
                ->whereBetween('created_at', [$start_time, $end_time])
                ->with('couponInfo:coupon,price');

            // 搜索条件
            if (!empty($searchTerm)) {
                $query->where(function ($q) use ($searchTerm) {
                    $q->where('account', $searchTerm)
                        ->orWhere('order_sn', $searchTerm)
                        ->orWhere('goods_name', 'like', '%' . $searchTerm . '%');
                });
            }

            // 关键修改：合并状态4（无副表）和状态2的数据
            if ($rechargeStatus == 4) {
                $query->where(function ($q) {
                    $q->doesntHave('OrderInfo') // 无副表数据
                    ->orWhereHas('OrderInfo', function ($sub) {
                        $sub->where('recharge_status', 2); // 副表状态为2
                    });
                });
            }
            // 处理其他状态
            elseif ($rechargeStatus != null) {
                if ($rechargeStatus == 0) {
                    $query->whereHas('OrderInfo', function ($subQuery) {
                        $subQuery->whereIn('recharge_status', [0, 3]);
                    });
                } else {
                    $query->whereHas('OrderInfo', function ($subQuery) use ($rechargeStatus) {
                        $subQuery->where('recharge_status', $rechargeStatus);
                    });
                }
            }

            // 关联预加载（适配状态4的特殊情况）
            $query->with(['OrderInfo' => function ($subQuery) use ($rechargeStatus) {
                $selectFields = [
                    'id', 'orderNum', 'gid', 'carmi', 'merchantOrderNum',
                    'goodsName', 'price', 'unitPrice', 'userName',
                    'rechargeMoney', 'recharge_time', 'recharge_status'
                ];

                // 状态4时只加载状态为2的副表数据
                if ($rechargeStatus == 4) {
                    $subQuery->select($selectFields)
                        ->where('recharge_status', 2);
                }
                // 其他状态保持原逻辑
                elseif (!empty($rechargeStatus)) {
                    $subQuery->select($selectFields)
                        ->where('recharge_status', $rechargeStatus);
                } else {
                    $subQuery->select($selectFields);
                }
            }]);

            // 分页查询
            $orders = $query->orderByDesc('created_at')->paginate(10);

            return $this->loadAndReturnOrders($orders);
        } catch (\Throwable $e) {
            return fails('订单查询失败，请稍后重试');
        }
    }
    /**
     * 加载商品信息并返回格式化订单数据
     */
    protected function loadAndReturnOrders($orders): JsonResponse
    {
        $goodsIds = $orders->getCollection()->pluck('gid')->filter()->unique();
        if ($goodsIds->isNotEmpty()) {
            $goodsInfo = NsSupplierGoods::with(['h5contentInfos' => function ($q) {
                $q->select('image_top', 'gid');
            }])
                ->whereIn('id', $goodsIds)
                ->select('id', 'profit', 'price')
                ->get()
                ->keyBy('id');

            $orders->getCollection()->transform(function ($order) use ($goodsInfo) {
                $order->goodInfo = $goodsInfo[$order->gid] ?? null;
                return $order;
            });
        }

        return successly($orders);
    }
}
